import { defineStore } from 'pinia'
import { useRouter } from 'vue-router'
import { ref } from 'vue'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useColumnStore } from '@/stores/columnStore'
import { useCardStore } from '@/stores/cardStore'
import { useUserStore } from '@/stores/userStore'
import { useModalStore } from '@/stores/modalStore'
import type { ErrorData, SearchResult } from '@/types/loginType'
export const useSearchInputStroe = defineStore('useSearchInputStroe', () => {
  const router = useRouter()
  const input = ref<HTMLInputElement | null>()
  function assignInputValue(value: string) {
    if (input.value) {
      input.value.value = value
    }
  }
  // 搜索分类
  // 0 专栏
  // 1 文章
  // 2 用户
  // 执行搜索
  async function searchKeyWords(value: string, type?: number) {
    if (value.trim()) {
      assignInputValue(value)
      router.push({ name: 'searchResult', query: { key: value } })
      const { search } = useAsyncAxios()
      const { status, data } = await search(value, type)
      if (status === 200) {
        const { columns, articles, users } = data as SearchResult
        const { assignListData, assignListOriginData } = useColumnStore()
        const { assignUsers, assignUsersOrigin } = useUserStore()
        const { assignCardData } = useCardStore()
        assignListOriginData(columns)

        assignUsersOrigin(users)
        assignUsers(1)
        assignCardData(articles)
      } else {
        const { changeData } = useModalStore()
        changeData({ status, data: data as ErrorData })
      }
    } else {
      assignInputValue('')
    }
  }

  return {
    input,
    searchKeyWords
  }
})
